// 统一的Toast提示函数
export const showToast = (title: string, icon: string) => {
  uni.showToast({
    title,
    icon,
    duration: 2000
  });
};

// 统一的Loading提示函数 - 支持字符串或对象参数
export const showLoading = (options?: string | { title?: string; mask?: boolean }) => {
  const config = typeof options === 'string' 
    ? { title: options, mask: true }
    : { title: '加载中', mask: true, ...options };
  
  uni.showLoading(config);
};

// 隐藏Loading
export const hideLoading = () => {
  uni.hideLoading();
};

// 统一的Alert提示函数
export const showAlert = (title: string, content: string, confirmText: string = '确定') => {
  return new Promise<void>((resolve) => {
    uni.showModal({
      title,
      content,
      showCancel: false,
      confirmText,
      success: () => {
        resolve();
      }
    });
  });
};

// 统一的Confirm提示函数
export const showConfirm = (title: string, content: string, confirmText: string = '确定', cancelText: string = '取消') => {
  return new Promise<boolean>((resolve) => {
    uni.showModal({
      title,
      content,
      confirmText,
      cancelText,
      success: (res) => {
        resolve(res.confirm);
      }
    });
  });
};



// 获取安全区域顶部距离
export const getSafeAreaTop = () => {
  return uni.getSystemInfoSync().safeAreaInsets?.top || 0;
};


// 跳转到指定页面
export const navigateTo = (url: string) => {
  uni.navigateTo({
    url
  });
};

export const switchTab = (url: string) => {
  uni.switchTab({
    url
  });
};

// 跳转到指定页面
export const navigateBack = () => {
  uni.navigateBack();
};

// ==================== 格式化工具函数 ====================

/**
 * 格式化数字，添加千位分隔符
 * @param num 要格式化的数字
 * @returns 带千位分隔符的格式化数字字符串
 * @example formatNumber(12345) => "12,345"
 */
export const formatNumber = (num: number | string | any): string => {
  // 使用Number转换确保输入是有效的数字，并提供默认值0
  const safeNum = Number(num);
  if (isNaN(safeNum)) return '0';
  return safeNum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

/**
 * 格式化货币，添加货币符号和千位分隔符
 * 货币金额会自动四舍五入取整
 * @param amount 要格式化的金额
 * @param symbol 货币符号，默认为"¥"
 * @returns 格式化后的货币字符串
 * @example formatCurrency(12345.67) => "¥12,346"
 * @example formatCurrency(12345, '$') => "$12,345"
 */
export const formatCurrency = (amount: number | string | any, symbol: string = '¥'): string => {
  const safeNum = Number(amount);
  if (isNaN(safeNum)) return symbol + '0';
  // 货币金额四舍五入取整
  const rounded = Math.round(safeNum);
  return symbol + formatNumber(rounded);
};